import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import useGetStorage from "@/hooks/useGetStorage";
import FcTextInput from "@/components/FcTextInput";
import FcModal from '@/components/FcModal';
import {LinearGradient} from "expo-linear-gradient";
import {Flex, Toast} from "@ant-design/react-native";
import {set_userInfo} from "@/store/reducer/login/loginSlice";
import {useSelector, useDispatch} from "react-redux";

import {
  useGetPhoneCodeMutation,
  useVerifiedUserPhoneMutation
} from "@/store/api/my/myApi";

import {useGetUserInfoMutation} from "@/store/api/login/loginApi";

type Props = {}

const phone = (props: Props) => {
  const [phone, setPhone] = useState('')
  const [newPhone, setNewPhone] = useState('')
  const [code, setCode] = useState('')
  const [userInfo, setUserInfo] = useState<any>({})
  const [phoneTiming, setPhoneTiming] = useState<any>(-1)
  const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
  const [replacePhoneOpen, setReplacePhoneOpen] = useState(false)
  
  const timer:any = useRef(null)
  const dispatch = useDispatch();

  const [getPhoneCodeFun] = useGetPhoneCodeMutation()
  const [verifiedUserPhoneFun] = useVerifiedUserPhoneMutation()
  const [getUserInfoFun] = useGetUserInfoMutation?.()

  let userData = useSelector(state => state.login.userInfo)
  
  useEffect(() => {
    useGetStorage('userInfo').then(res => {
      setPhone(res.userInfo.phone)
      setUserInfo(res.userInfo)
    })
  },[userData])

  const getScrollBodyInfo = ({height}) => {
    setPageScrollBodyH(height)
  }

  //获取手机验证码
  const getPhoneCode = (type:any) => {
    let phoneStr = type == 'phone' ? phone : newPhone

    if(!phoneStr || phoneStr.length != 11){
      Toast.info('请先填写11位数手机号');
      return
    }

    if(phoneTiming > 0){
      Toast.info('请' + phoneTiming + '秒后重试');
      return
    }

    let count = 60

    timer.current = setInterval(() => {
      count = count - 1
      setPhoneTiming(count)
      if(count <= 0){
        clearInterval(timer.current);
      }
    },1000)

    getPhoneCodeFun({id: userInfo.id, phone: phoneStr}).then(res => {})
  }

  const handleSubmit = (type:any) => {
    let phoneStr = type == 'phone' ? phone : newPhone

    const regex = /^1[3-9]\d{9}$/;

    if(!phoneStr || !code){
      Toast.info('手机号或者验证码不能为空！');
      return
    }

    if(!regex.test(phoneStr || phoneStr.length != 11)){
      Toast.info('手机号格式有误，请重新输入！');
      return
    }

    let params = {
      id: userInfo.id, 
      phone: phoneStr,
      phoneVerifiedSmsCode: code
    }

    verifiedUserPhoneFun(params).then(res => {
      Toast.info('验证成功')
      getUserInfoFun({}).then(res => {
        dispatch(set_userInfo(res.data?.result))

        setCode('')
        setPhoneTiming(-1)
        if(type == 'newPhone'){
          setReplacePhoneOpen(false)
        }
      })
    })
  }

  return (
    <PageScrollView
      isTransparentTab
      getPageScrollBodyInfo={getScrollBodyInfo}
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={'手机号绑定'}
        />
      }
      pageBottom={
        !userInfo.phoneVerifiedStatus ?
        <Flex justify='center' style={{height: 56, backgroundColor: '#FFF'}}>
          <FcButton
            onClick={() => handleSubmit('phone')}
            type='BjJB'
            colors={phone && code ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: '90%', height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName='提交'
          />
        </Flex>
        : null
      }
    >
      <View style={{padding: 10, borderRadius: 8, backgroundColor: '#FFF', height: pageScrollBodyH - 20}}>
        {
          userInfo.phoneVerifiedStatus ?
          <Flex direction='column'>
            <Text style={{marginTop: 50, fontSize: 15, fontWeight: '500'}}>已绑定手机号</Text>
            <Text style={{marginVertical: 10, fontSize: 17, fontWeight: 'bold'}}>{userInfo.phone}</Text>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>账号已与手机号绑定，可通过手机号登录</Text>
            <TouchableOpacity onPress={() => setReplacePhoneOpen(true)} style={{marginTop: 20}}>
              <Flex justify='center' style={{width: 147, height: 37, backgroundColor: '#F1F2F4', borderRadius: 8}}>
                <Text style={{color: '#334DB0'}}>更换手机号</Text>
              </Flex>
            </TouchableOpacity>
          </Flex>
          :
          <View>
            <Text style={{marginBottom: 5}}>手机号：</Text>
            <FcTextInput
              leftIconEle={
                <Text style={{fontFamily: 'FcIconFont', fontSize: 22, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe63b;</Text>
              }
              keyboardType='numeric'
              style={{marginBottom: 20}}
              inputStyle={{lineHeight: 20}}
              leftIconEleStyle={{paddingRight: 4}}
              text={phone} 
              placeholder={'请输入手机号'}
              onChangeText={setPhone}
              height={48}
            />

            <Text style={{marginBottom: 5}}>验证码：</Text>
            <FcTextInput
              leftIconEle={
                <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe606;</Text>
              }
              positionEle={
                <TouchableOpacity onPress={() => getPhoneCode('phone')}>
                  <Text style={{color: '#334DB0', fontSize: 15}}>{ phoneTiming < 0 ? '获取验证码' : phoneTiming == 0 ? '重新获取' : phoneTiming + 'S' }</Text>
                </TouchableOpacity>
              }
              inputStyle={{lineHeight: 20}}
              text={code} 
              placeholder={'请输入验证码'}
              onChangeText={setCode}
              height={48}
            />
          </View>
        }

        {/* 更换手机号弹窗 */}
        <FcModal
          isOpen={replacePhoneOpen}
          onFcModalClose={() => setReplacePhoneOpen(false)}
          titleText='更换手机号'
          titleBottomBorderWidth={0}
          bottom={
            <Flex justify='center' style={{height: 56, backgroundColor: '#FFF'}}>
              <FcButton
                onClick={() => handleSubmit('newPhone')}
                type='BjJB'
                colors={newPhone && code ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
                style={{width: '90%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='提交'
              />
            </Flex>
          }
        >
          <View style={{borderTopWidth: 1, borderColor: '#D8D8D8', padding: 24}}>
            <Text><Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>原手机号：</Text>{userInfo.phone}</Text>
            <Text style={{marginBottom: 8, marginTop: 12}}>新手机号：</Text>
            <FcTextInput
              leftIconEle={
                <Text style={{fontFamily: 'FcIconFont', fontSize: 22, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe63b;</Text>
              }
              keyboardType='numeric'
              inputStyle={{lineHeight: 20}}
              leftIconEleStyle={{paddingRight: 4}}
              text={newPhone} 
              placeholder={'请输入手机号'}
              onChangeText={setNewPhone}
              height={48}
            />

            <Text style={{marginBottom: 8, marginTop: 12}}>验证码：</Text>
            <FcTextInput
              leftIconEle={
                <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe606;</Text>
              }
              positionEle={
                <TouchableOpacity onPress={() => getPhoneCode('newPhone')}>
                  <Text style={{color: '#334DB0', fontSize: 15}}>{ phoneTiming < 0 ? '获取验证码' : phoneTiming == 0 ? '重新获取' : phoneTiming + 'S' }</Text>
                </TouchableOpacity>
              }
              inputStyle={{lineHeight: 20}}
              text={code} 
              placeholder={'请输入验证码'}
              onChangeText={setCode}
              height={48}
            />
          </View>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default phone

const styles = StyleSheet.create({
  code: {
    width: 111,
    height: 48,
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  }
})

